Ext.define('Seq.data.proxy.API', {
    extend: 'Ext.data.proxy.Ajax',
    alias: 'proxy.api',

    statics: {
        applyUrl(url) {
            var me = this, params = [];
            var value, values, idx = 0, reg = /\{[a-zA-Z0-9_]+\}/;
            while ((values = reg.exec(url)) != null) {
                value = values[0], params[idx] = value.substring(1, value.length - 1);
                url = url.replace(value, idx);
                idx++;
            }
            return {
                url: url,
                params: params
            };
        }
    },

    getUrl(request) {
        var me = this, v = Seq.data.proxy.API.applyUrl(me.callParent(arguments));
        var url = v.url, matchs = 0 < v.params.length ? v.params : me.matchs, params = request._params;
        if (matchs && 0 < matchs.length) {
            var i, match, len = matchs.length - 1;
            for (i = len; i >= 0; i--) { // 从后向前，避免参数超过10个
                match = matchs[i];
                url = url.replace('/' + i, '/' + params[match]);
                delete request._params[match];
            }
        }
        return url;
    },

    reader: {
        type: 'json',
        rootProperty: 'data',
        transform: {
            fn(data) {
                if (false == data.success) { // 服务器报错时，显示消息
                    Seq.Msg.error('服务器内部错误：<br/><br/>' + data.message);
                    return [];
                }
                return data;
            },
            scope: this
        }
    },

    listeners: {
        exception(proxy, request, operation, eOpts) {
            if (401 == request.status) {
                window.location.replace(window.location.origin + window.location.pathname);
            }
        }
    }

});